package com.qiaotongtianxia.loans.fragments;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.ViewFlipper;

import com.qiaotongtianxia.loans.R;
import com.qiaotongtianxia.loans.activity.CertificateActivity;
import com.qiaotongtianxia.loans.activity.DirectLoansActivity;
import com.qiaotongtianxia.loans.activity.LoansActivity;
import com.qiaotongtianxia.loans.functionInterface.IBaseRequestImp;
import com.qiaotongtianxia.loans.functionInterface.IWarningDialog;
import com.qiaotongtianxia.loans.net.Api;
import com.qiaotongtianxia.loans.util.BannerImageLoader;
import com.qiaotongtianxia.loans.util.CommonUtils;
import com.qiaotongtianxia.loans.util.Constants;
import com.qiaotongtianxia.loans.util.ToastUtil;
import com.qiaotongtianxia.loans.views.BaseTextView;
import com.qiaotongtianxia.loans.views.ButtonObserver;
import com.qiaotongtianxia.loans.views.DragLayout;
import com.qiaotongtianxia.loans.views.dialogs.DialogWarning;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lisen on 2017/12/14.
 *
 * @author lisen < 4533548588@qq.com >
 */

@SuppressWarnings("all")
public class LoansFragment extends BaseFragment implements DragLayout.DragListener{
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.viewFlipper)
    ViewFlipper viewFlipper;
    @BindView(R.id.tv_loansAmount)
    BaseTextView tvLoansAmount;
    @BindView(R.id.seekBar)
    SeekBar seekBar;
    @BindView(R.id.tv_least)
    BaseTextView tvLeast;
    @BindView(R.id.tv_most)
    BaseTextView tvMost;
    @BindView(R.id.btn_loans)
    ButtonObserver btn_loans;

    @BindView(R.id.dragLayout)
    DragLayout dragLayout;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;

    private final int CERTIFICATE = 100;

    private String[] fName = {"赵","钱","孙","李","周","吴","郑","王","崔","陈","褚","贾"};
//    private String[] names = {"用户李**成功借款","用户崔**成功借款","用户张*成功借款","用户刘**成功借款","用户牟**成功借款"};

    @Override
    public int getLayoutId() {
        return R.layout.fragment_loans;
    }

    @Override
    public Api onApiCreate() {
        return new Api(context);
    }

    @Override
    public void created(View view) {

        tvLoansAmount.setText("1000");
        btn_loans.setExtraEnable(true);
        dragLayout.setListener(this);
        initBanner();
        initFillpper();

        initSeekBar();
    }

    private void initSeekBar() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser){
                    tvLoansAmount.setText((progress+1000) + "");
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

                int result = 0;

                int progress = seekBar.getProgress() + 1000;
                int remainder = progress % 100;//余数
                int b = progress / 100;//整数
                if( remainder >= 50){
                    result = (b + 1) * 100;
                }else if(remainder < 50 ){
                    result = (b) * 100;
                }
                tvLoansAmount.setText(result+"");
                seekBar.setProgress(result-1000);
            }
        });
    }

    private void initBanner() {
        //资源文件
        List<Integer> images= new ArrayList<>();

        images.add(R.drawable.home_banner00);
        images.add(R.drawable.home_banner02);

        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setImageLoader(new BannerImageLoader());
        banner.setImages(images);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

            }
        });
        banner.start();
    }
    @SuppressLint("SetTextI18n")
    private void initFillpper() {
        for (int i = 0; i < fName.length; i++) {
            View view = LayoutInflater.from(context).inflate(R.layout.flipper_item, null);
            BaseTextView textView = (BaseTextView) view.findViewById(R.id.tv_Tip);
            int random = (int) Math.ceil(Math.random()*4);
            textView.setText("用户"+fName[i] +"**成功借款"+ (1000 * random + 100 * (int) (Math.random()*9))+"元");
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //....
                }
            });
            viewFlipper.addView(view);
        }
    }

    @OnClick(R.id.btn_loans)
    public void onViewClicked() {
        api.isCertificate(new IBaseRequestImp<Map<String,String>>() {
            @Override
            public void onRequestSuccess(Map<String,String> result) {
                ToastUtil.showShort(context,result.get("msg"));
                Intent intent;
                switch (CommonUtils.parseInt(result.get("auth_status"))){
                    case 0:
                    case 3://去实名认证
                        intent = new Intent(context, CertificateActivity.class);
                        startActivityForResult(intent,CERTIFICATE);
                        break;
                    case 1:
                        break;
                    case 2://去借款LoansActivity

                        isRegular();

                        break;
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CERTIFICATE && resultCode == Activity.RESULT_OK){
            Intent intent = new Intent(context, LoansActivity.class);
            intent.putExtra(Constants.LOANS_AMOUNT,tvLoansAmount.getText().toString());
            startActivity(intent);
        }
    }

    /**
     * 判断是否是老客户
     */
    private void isRegular() {
        api.isRegular(new IBaseRequestImp<Boolean>() {
            @Override
            public void onRequestSuccess(Boolean isRegular) {
                if (isRegular){
                    Intent intent = new Intent(context, DirectLoansActivity.class);
                    intent.putExtra(Constants.LOANS_AMOUNT,tvLoansAmount.getText().toString());
                    startActivity(intent);

                }else{
                    if (TextUtils.isEmpty(loansTip)){
                        requestTip();
                    }else{
                        showDialog(loansTip);
                    }
                }
            }

            @Override
            public void onRequestError(int errorCode, String errorMsg) {
                if (TextUtils.isEmpty(loansTip)){
                    requestTip();
                }else{
                    showDialog(loansTip);
                }
            }
        });
    }

    private String loansTip = "";
    private void requestTip() {
        api.loansTip(new IBaseRequestImp<String>() {
            @Override
            public void onRequestSuccess(String s) {
                loansTip = s;
                showDialog(s);
            }
        });
    }

    private void showDialog(String tip) {
        DialogWarning warning = new DialogWarning(context, new IWarningDialog() {
            @Override
            public void onConfirmListener() {
                Intent intent = new Intent(context, LoansActivity.class);
                intent.putExtra(Constants.LOANS_AMOUNT,tvLoansAmount.getText().toString());
                startActivity(intent);
            }
            @Override
            public void onCancelListener() {}
        });
        warning.setTitle("借款协议");
        warning.showTitle(View.VISIBLE);
        warning.setMsgHeight(CommonUtils.getScreenHeight(context)/2);
        warning.show(tip);
    }

    @Override
    public boolean isCanPullDown() {
        return CommonUtils.isReachTop(scrollView);
    }

    @Override
    public boolean isCanPullUp() {
        return CommonUtils.isReachBottom(scrollView);
    }

}
